//
//  AgreementViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/14.
//

import UIKit

class AgreementViewController: RViewController {

    // 隐私协议网址
    let privacyUrl = "https://checkmering.jp/privacy_policy"
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var cancelBtn: UIButton!
    @IBOutlet weak var agreeBtn: UIButton!
    /// 当为2时，已经全部同意，其它业务逻辑
    var agreeNumber = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.bgView.maskCorners(corners: UIRectCorner.init(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadi: 20)
        self.setupBtn()
        self.initTextView()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    // MARK: - function
    func setupBtn() {
        self.agreeBtn.layer.cornerRadius = self.agreeBtn.height / 2
        self.agreeBtn.layer.masksToBounds = true
        self.cancelBtn.setTitleColor(hexColor("3468E2"), for: .normal)
        self.cancelBtn.layer.cornerRadius = self.agreeBtn.height / 2
        self.cancelBtn.layer.borderWidth = 1
        self.cancelBtn.layer.borderColor = hexColor("3468E2")?.cgColor
        
        // 渐变色
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor(red: 0.36, green: 0.53, blue: 0.96, alpha: 1).cgColor, UIColor(red: 0.2, green: 0.4, blue: 0.88, alpha: 1).cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = self.agreeBtn.bounds
        bgLayer1.startPoint = CGPoint(x: 1.03, y: 0.67)
        bgLayer1.endPoint = CGPoint(x: 0.67, y: 0.67)
        self.agreeBtn.layer.insertSublayer(bgLayer1, at: 0)
        self.agreeBtn.setTitleColor(UIColor.white, for: .normal)
    }
    
    func initTextView() {
        let textStr = "こちらのアプリク-ションをご利用いただくにあたっては本プライパシ-ポリシ-をお読みいただき、内容についてご同意の上、ご利用いただくようお願いします。\n\n\(self.privacyUrl)"
        textView.delegate = self
        textView.textColor = hexColor("666666")
        
        ///设为true 在代理里面禁掉所有的交互事件
        textView.isEditable = true
        
        textView.autoresizingMask =  UIView.AutoresizingMask.flexibleHeight
        textView.isScrollEnabled = false
        let attStr = NSMutableAttributedString(string: textStr)
        
        //点击超链接
        attStr.addAttribute(NSAttributedString.Key.link, value: "privacyPolicy://", range: (textStr as NSString).range(of: self.privacyUrl))
        attStr.addAttribute(NSAttributedString.Key.font, value: regularFont(size: 14)!, range: (textStr as NSString).range(of: textStr))
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 10
        paragraphStyle.alignment = .center
        attStr.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: (textStr as NSString).range(of: textStr))
        
        textView.attributedText = attStr
        ///只能设置一种颜色
        textView.linkTextAttributes =  [
            NSAttributedString.Key.foregroundColor: hexColor("3468E2")!
        ]
    }
    
    ///  权限
    func setService() {
        self.titleLabel.text = "アプリのアクゼス許可要求"
        let textStr = "フアイルとメデイア:測定デ-タの共有フアイル(CSVフアイル、PDFフアイル)を保存するために使用します。位置情報:プル-トク-スでチエックミ-リングを検索するために使用します。カメラ:クラウド接続情報をQRコ-ドをスキャンして入力する際に使用します。"
        let attStr = NSMutableAttributedString(string: textStr)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 10
        paragraphStyle.alignment = .center
        attStr.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: (textStr as NSString).range(of: textStr))
        attStr.addAttribute(NSAttributedString.Key.font, value: regularFont(size: 14)!, range: (textStr as NSString).range(of: textStr))
        textView.attributedText = attStr
    }
    
    
    // 取消按钮 让其崩溃退出
    @IBAction func cancelBtnDidClicked(_ sender: Any) {
        let arr = [1]
        _ = arr[2]
    }
    
    // 同意按钮
    @IBAction func agreeBtnDidClicked(_ sender: Any) {
        self.agreeNumber += 1
        
        if self.agreeNumber == 1 {
            // 查看权限说明
            self.setService()
        }
        
        if self.agreeNumber == 2 {
            
            // 已同意用户协议
            CacheManager.manager.setValueForKey(AlreadyAgreement, true as NSCoding)
            
            // 跳转蓝牙搜索页
            let mainBundle = Bundle.main
            let main = UIStoryboard(name: "Main", bundle: mainBundle)
            let vc = main.instantiateViewController(withIdentifier: "ConnectViewController") as? ConnectViewController
            
//            let agree = ViewController.init()
//            self.navigationController?.pushViewController(agree, animated: true)
            UIApplication.shared.keyWindow?.rootViewController = vc
        }
    }
    
}

extension AgreementViewController: UITextViewDelegate {
    
    /// 禁止编辑
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        return false
    }
    
    /// 点击跳转
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.scheme == "privacyPolicy" {
            let webVC = SimpleWebViewController.init()
            webVC.url = self.privacyUrl
            self.navigationController?.pushViewController(webVC, animated: true)
            return false
        }
        return true
    }
    
}
